package com.tybbank.Activity;

import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.tybbank.Base.BaseActivity;
import com.tybbank.Bean.GGbean;
import com.tybbank.Login.LoginActivity;
import com.tybbank.MyApplication;
import com.tybbank.R;
import com.tybbank.Utils.Constant;
import com.tybbank.Utils.MD5Utils;
import com.tybbank.Utils.MyDialogUtils;
import com.tybbank.web.WebActivity;
import com.yuyh.library.imgsel.utils.LogUtils;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.util.Comparator;
import java.util.SortedMap;
import java.util.TreeMap;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

/**
 * Created by Administrator on 2019/3/13.
 */

public class TaoCanBuyActivity extends BaseActivity {
    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.tv_tc_name)
    TextView tvTcName;
    @BindView(R.id.tv_tc_money)
    TextView tvTcMoney;
    @BindView(R.id.tv_tc_time)
    TextView tvTcTime;
    @BindView(R.id.tv_tc_huoqi_time)
    TextView tvTcHuoqiTime;
    @BindView(R.id.tv_type)
    TextView tvType;
    @BindView(R.id.bt_enter)
    Button btEnter;
    @BindView(R.id.et_money)
    EditText etMoney;
    @BindView(R.id.tv_zengsong)
    TextView tvZengsong;
    @BindView(R.id.et_pwd)
    EditText etPwd;
    @BindView(R.id.tv_keyongshuliang)
    TextView tvKeyongshuliang;
    @BindView(R.id.ck_checkbox)
    CheckBox ckCheckbox;
    @BindView(R.id.text_wuyong)
    TextView textWuyong;
    private String id;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_buyxq);
        ButterKnife.bind(this);
        toolbar(toolbar, getIntent().getStringExtra("title"), R.mipmap.left);
        tvTcMoney.setText(getIntent().getStringExtra("adtio") + "%");
        tvType.setText(getIntent().getStringExtra("name"));
        tvTcHuoqiTime.setText(getIntent().getStringExtra("days"));
        tvTcTime.setText(getIntent().getStringExtra("term"));
        try {
            tvKeyongshuliang.setText(getString(R.string.keyongshuliang) + ": " + getIntent().getStringExtra("money"));
        } catch (Exception e) {
        }
        etMoney.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                if (!TextUtils.isEmpty(etMoney.getText().toString().trim())) {
                    double aDouble = Double.parseDouble(etMoney.getText().toString().trim());
                    double bz = Double.parseDouble(getIntent().getStringExtra("adtio"));
                    tvZengsong.setText("赠送:" + format2((aDouble * bz) / 100));
                } else {
                    tvZengsong.setText("赠送:0.00");
                }
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });
    }

    //保留小数点后两位
    public static String format2(double value) {
        DecimalFormat df = new DecimalFormat("0.00");
        df.setRoundingMode(RoundingMode.HALF_UP);
        return df.format(value);
    }

    @OnClick({R.id.tv_tc_huoqi_time, R.id.bt_enter, R.id.text_wuyong})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.text_wuyong:
                Intent intent = new Intent(this, WebActivity.class);
                intent.putExtra("title", getString(R.string.fuwutiaokuan));
                intent.putExtra("url", Constant.tisuxieyi);
                startActivity(intent);
                break;
            case R.id.bt_enter:

                if (TextUtils.isEmpty(etMoney.getText().toString().trim())) {
                    showTips(getString(R.string.buymoney));
                } else if (TextUtils.isEmpty(etPwd.getText().toString().trim())) {
                    showTips(getString(R.string.paypwdhint));
                } else {
                    if (ckCheckbox.isChecked()) {
                        init();
                    } else {
                        showTips(getString(R.string.xieyitoast));
                    }
                }
                break;
        }
    }

    private void init() {
        String time = MD5Utils.getTime();
        SortedMap<String, String> parameters = new TreeMap<String, String>(
                new Comparator<String>() {
                    public int compare(String obj1, String obj2) {
                        // 降序排序
                        return obj1.compareTo(obj2);
                    }
                });
        parameters.put("uuid", MyApplication.uuid);
        parameters.put("token", MyApplication.token);
        parameters.put("id", getIntent().getStringExtra("id"));
        parameters.put("TimeStamp", time);
        parameters.put("pay_pwd", MD5Utils.md5Password(etPwd.getText().toString().trim()));
        parameters.put("money", etMoney.getText().toString().trim());
        String sign = MD5Utils.createSign(parameters);
        final Dialog dialog = MyDialogUtils.createLoadingDialog(this, getString(R.string.loading));
        dialog.show();
        OkHttpUtils
                .post()
                .url(Constant.Current_current_pay)
                .addParams("uuid", MyApplication.uuid)
                .addParams("id", getIntent().getStringExtra("id"))
                .addParams("token", MyApplication.token)
                .addParams("pay_pwd", MD5Utils.md5Password(etPwd.getText().toString().trim()))
                .addParams("money", etMoney.getText().toString().trim())
                .addParams("TimeStamp", time)
                .addParams("Sign", sign)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        e.printStackTrace();
                        dialog.dismiss();
                        Toast.makeText(getBaseContext(), getString(R.string.error), Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        LogUtils.e("TAG买入活期" + response.toString());
                        dialog.dismiss();
                        postReponse(response);
                    }

                    public void postReponse(String json) {
                        try {
                            GGbean enterBean = new Gson().fromJson(json, new TypeToken<GGbean>() {
                            }.getType());
                            int a = enterBean.getCode();
                            if (a == 1011) {
                                showTips(enterBean.getMsg());
                                TaoCanBuyActivity.this.finish();
                                setResult(RESULT_OK);
                            } else if (a == 1004) {
                                Intent intent = new Intent(getBaseContext(), LoginActivity.class);
                                startActivity(intent);
                                return;
                            } else {
                                showTips(enterBean.getMsg());
                            }
                        } catch (Exception e) {

                        }

                    }
                });

    }

}
